﻿using Autofac;
using Catastrophe.AutoSulution.EDC;
using Catastrophe.BasePC.UI.DbDal;
using Catastrophe.BasePC.UI.File;
using Catastrophe.BasePC.UI.Model;
using Catastrophe.BasePC.UI.Model;
using Catastrophe.BasePC.UI.SystemIni;
using Catastrophe.BasePC.UI.SystemIni.BaseData;
using Catastrophe.BasePC.UI.UI;
using Catastrophe.Common.AttributeEx;
using Catastrophe.Common.ObjM;
using Catastrophe.Initialize;
using Catastrophe.Initialize.IOCProvier;
using Catastrophe.Log;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.JavaScript;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using static Org.BouncyCastle.Math.EC.ECCurve;

namespace Catastrophe.BasePC.UI
{
    /// <summary>
    /// 启动类
    /// </summary>
    public static class FrameLoad
    {

        public static void Start(bool runLoginFrm = true, bool runPreloadFrm = true, string defaultUserName = "admin", string defaultPwd = "", bool multiStart = false, Window cusMainFrm = null, [CallerFilePath] string path = null)
        {
            if (!FrameEnvironment.IsDebug)
            {
                defaultPwd = "";
            }
            else
            {
                FrameEnvironment.SourceCodePath = path[..path.LastIndexOf("\\")];
            }
            FrameEnvironment.CancelPower = !runLoginFrm;
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Assembly callingAssembly = Assembly.GetCallingAssembly();
            CatastropheInitializer.FrameLoadIni(callingAssembly);
            FrameLoad.SystemInitialize();

            Load baseLoginFrm = new Load();

            var value = EnDeCode.GetStrSplit<int>(FileConfigIni.GetFileConfig.LoginFrmSize, ",");
            if (value.Item1 && value.Item2.Count > 1)
            {
                baseLoginFrm.Width = value.Item2[0];
                baseLoginFrm.Height = value.Item2[1];
            }
      
            baseLoginFrm.SetDefaultLoginInfo(defaultUserName, defaultPwd);
            baseLoginFrm.CloseAction += BaseLoginFrm_CloseAction;
            baseLoginFrm.Show();
        }

        private static void BaseLoginFrm_CloseAction(Window obj, SysUserEntity entity, bool checkValue)
        {
            if (checkValue)
            {
                if (entity != null)
                {
                    FrameEnvironment.UserName = entity.UserName;
                    FrameEnvironment.UserNo = entity.UserNo;
                    FrameEnvironment.Identify = entity.Identify;
                    FrameEnvironment.Depart = entity.Depart;
                    FrameEnvironment.AuthorizeType = entity.AuthorizeType;
                    Ggo<List<SysMenuEntity>>.GetObj = new SysMenuDal().QueryBaseMenuNode(FrameEnvironment.UserName, FrameEnvironment.UserNo, FrameEnvironment.Depart, FrameEnvironment.Identify, FrameEnvironment.AuthorizeType, FrameEnvironment.IsAdmin).ToList();
                    BaseResponse<Window> byName = CatastropheProvider.GetByName<Window>(DataIniEntity.name_Main);
                    if (byName.Success)
                    {

                        var value = EnDeCode.GetStrSplit<int>(FileConfigIni.GetFileConfig.SystemCacheFrm, ",");
                        if (value.Item1 && value.Item2.Count > 1)
                        {
                            byName.Content.Width = value.Item2[0];
                            byName.Content.Height = value.Item2[1];
                        }
                        Application.Current.MainWindow = byName.Content;
                        Application.Current.MainWindow.Show();
                        obj.Hide();
                    }
                    else
                    {
                        MessageBox.Show(byName.Message);
                    }
                }
            }
            else
            {
                MessageBox.Show("用户名或者密码校验错误");
            }
        }


        private static void SystemInitialize()
        {
            try
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                BuildAttribute.RunSystemIniMethod<FileConfigIni>();
                BuildAttribute.RunSystemIniMethod<LogConfigIni>();
                FrameLoad.PeanutRegister();
                stopwatch.Stop();
                long elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
            }
            catch (Exception innerException)
            {
                throw new Exception("加载配置参数失败！", innerException);
            }
        }

        private static void PeanutRegister()
        {
            ContainerBuilder containerBuilder = new ContainerBuilder();
            containerBuilder.RegisterType<SysDictionaryDal>().As<ISysDictionaryDal>();
            containerBuilder.RegisterType<SysEncodeDal>().As<ISysEncodeDal>();
            containerBuilder.RegisterType<SysUserDal>().As<IBaseUserDal>();
            CatastropheProvider.Register(containerBuilder.Build());
        }


        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            ExceptionUtil.ShowDialog(ex, "发生未处理的异常...");
            LogSession.DbLog.WriteLogNormal(LogLevelEnum.Fatal, "发生未处理的异常...", ex, "",
                "CurrentDomain_UnhandledException",
                "Catastrophe.BasePC.UI\\FrameLoad.cs", 185);
        }
    }
}
